/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package irsystem.scenario.method;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

/**
 *
 * @author Cerulean
 */
public class TermVectorSpace
{
    HashMap<String, Double> vector;

    public TermVectorSpace(HashMap<String, Double> vector)
    {
        this.vector = vector;
    }
    
    public double getValue(String term)
    {
        return vector.get(term);
    }
    
    public boolean isTermExist(String term)
    {
        return vector.containsKey(term);
    }
    
    public void addValue(String term, double value)
    {
        vector.put(term, value);
    }
    
    public void removeValue(String term)
    {
        vector.remove(term);
    }
    
    public void updateValue(String term,double value)
    {
        if(vector.containsKey(term))
        {
            vector.remove(term);
        }
        addValue(term, value);
    }
    
    public TermVectorSpace scalarProduct(double val)
    {
        HashMap<String,Double> map=new HashMap<String, Double>();
        String[] keyArr=(String[]) vector.keySet().toArray();
        for(int i=0;i<keyArr.length;i++)
        {
            map.put(keyArr[i], val*vector.get(keyArr[i]));
        }
        return new TermVectorSpace(map);
    }
    
    public TermVectorSpace elementProduct(TermVectorSpace anotherVector)
    {
        TermVectorSpace va=this,vb=anotherVector;
        if(va.vector.size()>vb.vector.size())
        {
            va=anotherVector;
            vb=this;
        }
        HashMap<String,Double> map=new HashMap<String, Double>();
        Set<String> set=va.vector.keySet();
        Iterator<String> it=set.iterator();
        while(it.hasNext())
        {
            String key=it.next();
            if(vb.vector.containsKey(key))
            {
                double val=va.getValue(key)*vb.getValue(key);
                if(val!=0)
                {
                    map.put(key, val);
                }
            }
        }
        return new TermVectorSpace(map);
    }
    
    public double dotProduct(TermVectorSpace anotherVector)
    {
        double product=0.0;
        TermVectorSpace va=this,vb=anotherVector;
        if(va.vector.size()>vb.vector.size())
        {
            va=anotherVector;
            vb=this;
        }
        //Set<String> set=va.vector.keySet();
        Iterator<Entry<String,Double>> it=va.vector.entrySet().iterator();
        while(it.hasNext())
        {
            Entry<String,Double> entry=it.next();
            if(vb.vector.containsKey(entry.getKey()))
            {
                product+=va.getValue(entry.getKey())*vb.getValue(entry.getKey());
            }
        }
        return product;
    }

    public HashMap<String, Double> getVector() {
        return vector;
    }
    
}
